package com.ljkj.cordial.chat.activity;

import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;

import com.lanjiu.lib.imclient.ims.IMSContacts;
import com.ljkj.cordial.chat.R;
import com.ljkj.cordial.chat.bean.Canstants;
import com.ljkj.cordial.chat.dao.DbController;
import com.ljkj.cordial.chat.dao.notify.GroupTable;
import com.ljkj.cordial.chat.ui.AppEventActivity;
import com.ljkj.cordial.chat.ui.views.GroupNoticeSetView;
import com.nic.view.util.JToast;
import com.nic.view.widget.ContainsEmojiEditText;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 群公告设置
 */
public class GroupNoticeSetActivity extends AppEventActivity<GroupNoticeSetView> {


    @BindView(R.id.et_group_notice)
    ContainsEmojiEditText etGroupNotice;

    private String targetId;

    @Override
    public int getContentLayoutId() {
        return R.layout.activity_group_notice_set;
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
        targetId = getIntent().getStringExtra(Canstants.EXTRA_KEY_GROUP_ID);

        getToolbar().setTitle("群公告");
        getToolbarRightTv().setVisibility(View.VISIBLE);
        getToolbarRightTv().setText("保存");
        getToolbarRightTv().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(etGroupNotice.getText())) {
                    etGroupNotice.setError("不能为空");
                    return;
                }

                obtainView().doSetGroupNotice(targetId, etGroupNotice.getText().toString());
            }
        });
    }

    public static void jumpTo(Activity activity, String groupId) {
        Intent intent = new Intent(activity, GroupNoticeSetActivity.class);
        intent.putExtra(Canstants.EXTRA_KEY_GROUP_ID, groupId);
        activity.startActivityForResult(intent, Canstants.KEY_GROUP_NOTICE_RESULT);
    }

    @Override
    protected GroupNoticeSetView bindNettyMessageView() {
        return new GroupNoticeSetView((code, msg) -> {
            if (code == IMSContacts.ResponseCode.SUCCESS) {
                String announcementContent = etGroupNotice.getText().toString();
                GroupTable groupTable = GroupTable.queryRowByGroupId(targetId);
                if (groupTable != null) {
                    groupTable.setAnnouncementContent(announcementContent);
                    DbController.getInstance().getWrite().getGroupTableDao().update(groupTable);
                }

                Intent intent = getIntent();
                intent.putExtra(Canstants.KEY_GROUP_NOTICE, announcementContent);
                setResult(Canstants.KEY_GROUP_NOTICE_RESULT, intent);
                finish();
            } else {
                JToast.showShort(GroupNoticeSetActivity.this, msg);
            }
        });
    }
}
